
#include <apr_pools.h>
#include "../iface/APRInterface.h"
#include "../utils/StringUtils.h"
#include "../iface/debug.h"
#include "XMLReader.h"

XMLReader::XMLReader()
{
   ctxt = xmlNewParserCtxt();
   if (ctxt == NULL)
      errprint("failed to get new XML reader context");
}

XMLReader::~XMLReader()
{
   if (ctxt) xmlFreeParserCtxt(ctxt);
}

xmlDocPtr XMLReader::XMLRead(const char *buffer, int size, int *success, int *vsuccess)
{
   xmlDocPtr doc = xmlCtxtReadMemory(ctxt, buffer, size, NULL, NULL, (vsuccess) ? XML_PARSE_DTDVALID : 0);
   if (success != NULL) *success = (doc != NULL);
   if (vsuccess != NULL) *vsuccess = ctxt->valid;
   if (!doc) errprint("failed to parse XML file");
   if (!(ctxt->valid)) errprint("failed to validate XML file");
   xmlCtxtReset(ctxt);
   return doc;
}

xmlDocPtr XMLReader::XMLRead(const char *xmlfilename, int *success)
{
   return XMLRead(xmlfilename, success, NULL);
}

xmlDocPtr XMLReader::XMLRead(const char *xmlfilename, int *success, int *vsuccess)
{
   apr_status_t status;
   apr_pool_t *mp;
   status = apr_pool_create(&mp, NULL);
   CheckAPRError(status);
   char *xmlstring = NULL;
   int retval = StringUtils::ReadFileToString(&xmlstring, xmlfilename, mp);
   if (retval) { errprint("failed to read file '%s'", xmlfilename); return NULL; }
   xmlDocPtr doc = XMLRead(xmlstring, strlen(xmlstring), success, vsuccess);
   apr_pool_destroy(mp);
   return doc;
}
